package com.bdqn.t382.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

public class PrinterAspect {
    private static final Logger logger = LoggerFactory.getLogger(PrinterAspect.class);
    private Random random = new Random();

    @Before("execution(* com.example.printer.Printer.print(..))")
    public void beforePrint(JoinPoint joinPoint) {
        int randomNum = random.nextInt(10);
        if (randomNum < 5) {
            logger.info("自检正常，准备开始打印。");
        } else {
            RuntimeException exception = new RuntimeException("自检出现异常，无法打印。");
            logger.error("自检失败", exception);
            throw exception;
        }
    }

    @AfterReturning("execution(* com.example.printer.Printer.print(..))")
    public void afterPrint(JoinPoint joinPoint) {
        logger.info("打印成功。");
    }

    @AfterThrowing(pointcut = "execution(* com.example.printer.Printer.print(..))", throwing = "ex")
    public void afterThrowing(JoinPoint joinPoint, RuntimeException ex) {
        logger.error("打印过程中出现异常：{}", ex.getMessage());
    }

    @After("execution(* com.example.printer.Printer.print(..))")
    public void finalPrint(JoinPoint joinPoint) {
        logger.info("打印操作结束。");
    }
}
